/**
 * RAGFlow AI API接口
 */

// RAGFlow配置
const RAGFLOW_CONFIG = {
  baseURL: 'http://10.223.9.4/api/v1',
  chatId: '42bdfaeaba4011f080667e3d45512fa6',
  apiKey: 'ragflow-Y3NjMxOTgyYjNmOTExZjBiMGY2MzJhNz',
  model: 'deepseek-r1:1.5b'
}

/**
 * 发送聊天消息到RAGFlow（流式模式）
 * @param {Object} data - 请求参数
 * @param {string} data.message - 用户消息
 * @param {Array} data.history - 历史消息记录（可选）
 * @returns {Promise<Response>} fetch Response对象
 */
export async function sendRagflowChatStream(data) {
  const { message, history = [] } = data
  
  // 构建消息数组，包含历史记录
  const messages = []
  
  // 添加历史消息（最多保留10条）
  if (history && history.length > 0) {
    const recentHistory = history.slice(-10)
    messages.push(...recentHistory.map(msg => ({
      role: msg.role === 'assistant' ? 'assistant' : 'user',
      content: msg.content
    })))
  }
  
  // 添加当前用户消息
  messages.push({
    role: 'user',
    content: message
  })
  
  const url = `${RAGFLOW_CONFIG.baseURL}/chats_openai/${RAGFLOW_CONFIG.chatId}/chat/completions`
  
  const requestBody = {
    model: RAGFLOW_CONFIG.model,
    messages: messages,
    stream: true
  }
  
  console.log('🔵 发送RAGFlow请求:', {
    url,
    body: requestBody
  })
  
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${RAGFLOW_CONFIG.apiKey}`
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      const errorText = await response.text()
      console.error('❌ RAGFlow请求失败:', response.status, errorText)
      throw new Error(`RAGFlow API错误: ${response.status} - ${errorText}`)
    }
    
    console.log('✅ RAGFlow响应成功')
    return response
    
  } catch (error) {
    console.error('❌ RAGFlow连接失败:', error)
    throw error
  }
}

/**
 * 检查RAGFlow服务健康状态
 * @returns {Promise<Object>} 健康状态信息
 */
export async function checkRagflowHealth() {
  try {
    const url = `${RAGFLOW_CONFIG.baseURL}/chats_openai/${RAGFLOW_CONFIG.chatId}/chat/completions`
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${RAGFLOW_CONFIG.apiKey}`
      },
      body: JSON.stringify({
        model: RAGFLOW_CONFIG.model,
        messages: [{ role: 'user', content: 'ping' }],
        stream: false
      })
    })
    
    return {
      status: response.ok ? 'healthy' : 'unhealthy',
      statusCode: response.status
    }
  } catch (error) {
    console.error('❌ RAGFlow健康检查失败:', error)
    return {
      status: 'unhealthy',
      error: error.message
    }
  }
}

/**
 * 更新RAGFlow配置
 * @param {Object} config - 新的配置项
 */
export function updateRagflowConfig(config) {
  if (config.baseURL) RAGFLOW_CONFIG.baseURL = config.baseURL
  if (config.chatId) RAGFLOW_CONFIG.chatId = config.chatId
  if (config.apiKey) RAGFLOW_CONFIG.apiKey = config.apiKey
  if (config.model) RAGFLOW_CONFIG.model = config.model
}

/**
 * 获取当前RAGFlow配置
 * @returns {Object} 当前配置
 */
export function getRagflowConfig() {
  return { ...RAGFLOW_CONFIG }
}

export default {
  sendRagflowChatStream,
  checkRagflowHealth,
  updateRagflowConfig,
  getRagflowConfig
}


